import React, { useEffect, useState } from "react";
import "./Station.css";
import {
  message, Spin, Empty,
  Table, Button, Space,
  Drawer, Form, Input,
} from 'antd';
import { 
  giveRequest,
  getstationinfo,
  deletestation,
  modifystationinfo,
  addstation,
} from "../../../lib/apiconfig";

const { Column } = Table;

/**
 * @description 关于站点的管理组件
 */
const Station = () => {
  const [data, setData] = useState(undefined);
  const [drawer, setDrawer] = useState(false);
  const [freshAction, setFreshAction] = useState(false);
  const [title, setTitle] = useState("新增站点");
  const [currentMsg, setCurrentMsg] = useState({ id: "", name: "", longitude: "", dimensionality: "" });
  const [form] = Form.useForm();


  useEffect(() => {
    giveRequest(getstationinfo(0,1000), "GET", null, res => {
      const status = res.status;
      if ( status === "fail" ) {
        message.error("获取数据失败");
        setData(null);
      } else {
        res.data.forEach(item => {
          item["key"] = item.id;
        });
        setData(res.data);
      }
    });
  }, [freshAction]);

  // 新增站点
  const newStation = () => {
    const message = { id: "", name: "", longitude: "", dimensionality: "" };
    setTitle("新增站点");
    setCurrentMsg(message);
    form.setFieldsValue(message);
    setDrawer(true);
  }

  // 修改站点信息
  const modifyStationInfo = record => {
    const message = { id: record.id, name: record.name, longitude: record.longitude, dimensionality: record.dimensionality };
    setTitle("修改站点信息");
    setCurrentMsg(message);
    form.setFieldsValue(message);
    setDrawer(true);
  };

  // 删除站点
  const deleteStation = record => {
    giveRequest(
      deletestation,
      "POST",
      {
        status: "deletestation",
        data: {
          id: record.id,
          name: record.name,
        }
      },
      res => {
        const status = res.status;
        if ( status === "success" ) {
          message.success("删除成功");
          setFreshAction(!freshAction);
        } else {
          message.error("删除失败!");
        }
      }
    );
  };
  
  // 提交表单
  const submit = () => {
    if ( title === "修改站点信息" && currentMsg && currentMsg.id && currentMsg.name && currentMsg.longitude && currentMsg.dimensionality ) {
      giveRequest(
        modifystationinfo,
        "POST",
        {
          status: "modifystationinfo",
          data: {
            id: currentMsg.id,
            name: currentMsg.name,
            longitude: currentMsg.longitude,
            dimensionality: currentMsg.dimensionality,
          }
        },
        res => {
          const status = res.status;
          if ( status === "success" ) {
            message.success("修改成功");
            setDrawer(false);
            setFreshAction(!freshAction);
          } else {
            message.error("修改失败!");
          }
        }
      );
    } else if ( title === "新增站点" && currentMsg && currentMsg.name && currentMsg.longitude && currentMsg.dimensionality ) {
      giveRequest(
        addstation,
        "POST",
        {
          status: "addstation",
          data: {
            name: currentMsg.name,
            longitude: currentMsg.longitude,
            dimensionality: currentMsg.dimensionality,
          }
        },
        res => {
          const status = res.status;
          if ( status === "fail" ) {
            message.error("添加失败!");
          } else if ( status === "warning" ) {
            message.warn("该站点已存在!");
          } else {
            message.success("添加成功");
            setDrawer(false);
            setFreshAction(!freshAction);
          }
        }
      );
    } else {
      message.warn("站点信息不能为空!");
    }
  };


  return (
    <div className="Station-page">
    { function() {
      if ( data === undefined )
        return (
          <div className="Station-loading flex-column-center-center">
            <Spin size="large" />
          </div>
        );
      else if ( data === null ) 
        return (
          <div className="Station-failed flex-column-center-center">
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          </div>
        );
      else
        return (
          <div className="Station-content flex-column-center-center">
            <Table dataSource={data} className="Station-table" pagination={{ pageSize: 9, style: { marginRight: "30px" } }}>
              <Column title="站点ID" dataIndex="id" key="id" />
              <Column title="站点名称" dataIndex="name" key="name" />
              <Column title="等待人数" dataIndex="waitingnumber" key="waitingnumber" />
              <Column
                title="操作"
                key="action"
                render={record => (
                  <Space size="middle">
                    <Button 
                      type="link"
                      style={{ padding: 0 }}
                      onClick={() => modifyStationInfo(record)}
                    >
                      修改信息
                    </Button>
                    <Button 
                      type="link"
                      style={{ padding: 0 }}
                      onClick={() => deleteStation(record)}
                    >
                      删除站点
                    </Button>
                  </Space>
                )}
              />
            </Table>
            <div className="Station-new-account flex-row-start-center">
              <Button 
                type="primary" 
                size="large" 
                style={{ width: 150 }}
                onClick = {() => newStation()}
              >
                新增站点
              </Button>
            </div>
            <Drawer
              title={title}
              width={360}
              onClose={() => setDrawer(false)}
              visible={drawer}
              footer={
                <div style={{ textAlign: 'right' }}>
                  <Button 
                    style={{ marginRight: 16, width: 80 }}
                    onClick={() => setDrawer(false)}
                  >
                    取消
                  </Button>
                  <Button 
                    type="primary"
                    style={{ width: 80 }}
                    onClick={submit}
                  >
                    提交
                  </Button>
                </div>
              }
            >
              <Form 
                layout="vertical" 
                hideRequiredMark
                form={form}
                onValuesChange={data => {
                  const new_station_info = JSON.parse(JSON.stringify(currentMsg));
                  Object.keys(data).forEach(item => {
                    new_station_info[item] = data[item];
                  });
                  setCurrentMsg(new_station_info);
                }}
              >
              { title === "修改站点信息" ? (
                <Form.Item label="站点ID" name="id" rules={[{ required: true, message: "站点ID不能为空!" }]}>
                  <Input disabled />
                </Form.Item>
              ) : null }
                <Form.Item label="站点名称" name="name" rules={[{ required: true, message: "站点名称不能为空!" }]}>
                  <Input placeholder="请输入站点名称~" />
                </Form.Item>
                <Form.Item label="站点位置: 经度" name="longitude" rules={[{ required: true, message: "站点位置不能为空!" }]}>
                  <Input placeholder="请输入站点位置: 经度~" />
                </Form.Item>
                <Form.Item label="站点位置: 纬度" name="dimensionality" rules={[{ required: true, message: "站点位置不能为空!" }]}>
                  <Input placeholder="请输入站点位置: 纬度~" />
                </Form.Item>  
              </Form>
            </Drawer>
          </div>
        );
    } ()}
    </div>
  );
}

export default Station;